﻿using ReaLTaiizor.Controls;
using System;
using System.Drawing;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;
using TouchSocket.Core;
using TouchSocket.Sockets;
using TcpClient = TouchSocket.Sockets.TcpClient;

namespace 数据转发工具
{
    public partial class FormV1 : Form
    {
        public FormV1()
        {
            InitializeComponent();
        }
        TcpService service = new TcpService();
        TcpClient tcpClientLeft = new TcpClient();
        TcpClient tcpClientRight = new TcpClient();
        private void Form1_Load(object sender, EventArgs ev)
        {
            dungeonComboBox1.Items.Add("TcpServer");
            dungeonComboBox1.Items.Add("TcpClient");
            //dungeonComboBox1.Items.Add("COM");
            dungeonComboBox1.SelectedIndex = 0;
            dungeonComboBox2.Items.Add("TcpServer");
            dungeonComboBox2.Items.Add("TcpClient");
            //dungeonComboBox2.Items.Add("COM");
            dungeonComboBox2.SelectedIndex = 0;

            dungeonTextBox1.Text = "0.0.0.0";
            dungeonTextBox2.Text = "15000";
            dungeonTextBox3.Text = "15001";
            dungeonTextBox4.Text = "0.0.0.0";

            //
            service.Connecting = (client, e) => { return EasyTask.CompletedTask; };//有客户端正在连接
            service.Connected = (client, e) => 
            {
                client.ResetId($"ServicePort:{client.ServicePort}-IPPort:{client.IP}:{client.Port}-{DateTime.Now.ToString("HH:mm:ss:ffff")}");
                this.Invoke((EventHandler)delegate
                {
                    SentOnlineColor();
                });
                return EasyTask.CompletedTask; 
            };
            service.Disconnecting = (client, e) => { return EasyTask.CompletedTask; };//有客户端正在断开连接，只有当主动断开时才有效。
            service.Disconnected = (client, e) => 
            {
                this.Invoke((EventHandler)delegate
                {
                    SentOnlineColor();
                });
                return EasyTask.CompletedTask; 
            };
            service.Received = (client, e) =>
            {
                var ids = service.GetIds();
                foreach (var id in ids)
                {
                    if (!id.Contains($"ServicePort:{client.ServicePort}"))
                    {
                        service.Send(id, e.ByteBlock);
                    }
                }
                if (tcpClientLeft.Online)
                {
                    tcpClientLeft.Send(e.ByteBlock.Buffer, 0, e.ByteBlock.Len);
                }
                if (tcpClientRight.Online)
                {
                    tcpClientRight.Send(e.ByteBlock.Buffer, 0, e.ByteBlock.Len);
                }

                return EasyTask.CompletedTask;
            };
            //启动
            service.Setup(new TouchSocketConfig());
            service.Start();


            tcpClientLeft.Connecting = (client, e) => { return EasyTask.CompletedTask; };//即将连接到服务器，此时已经创建socket，但是还未建立tcp
            tcpClientLeft.Connected = (client, e) => 
            {
                this.Invoke((EventHandler)delegate
                {
                    SentOnlineColor();
                });
                return EasyTask.CompletedTask; 
            };
            tcpClientLeft.Disconnecting = (client, e) => { return EasyTask.CompletedTask; };//即将从服务器断开连接。此处仅主动断开才有效。
            tcpClientLeft.Disconnected = (client, e) => 
            {
                this.Invoke((EventHandler)delegate
                {
                    SentOnlineColor();
                });
                return EasyTask.CompletedTask; 
            };
            tcpClientLeft.Received = (client, e) =>
            {
                var ids = service.GetIds();
                foreach (var id in ids)
                {
                    service.Send(id, e.ByteBlock);
                }
                if (tcpClientRight.Online)
                {
                    tcpClientRight.Send(e.ByteBlock.Buffer, 0, e.ByteBlock.Len);
                }
                return EasyTask.CompletedTask;
            };


            tcpClientRight.Connecting = (client, e) => { return EasyTask.CompletedTask; };//即将连接到服务器，此时已经创建socket，但是还未建立tcp
            tcpClientRight.Connected = (client, e) =>
            {
                this.Invoke((EventHandler)delegate
                {
                    SentOnlineColor();
                });
                return EasyTask.CompletedTask;
            };
            tcpClientRight.Disconnecting = (client, e) => { return EasyTask.CompletedTask; };//即将从服务器断开连接。此处仅主动断开才有效。
            tcpClientRight.Disconnected = (client, e) =>
            {
                this.Invoke((EventHandler)delegate
                {
                    SentOnlineColor();
                });
                return EasyTask.CompletedTask;
            };
            tcpClientRight.Received = (client, e) =>
            {
                var ids = service.GetIds();
                foreach (var id in ids)
                {
                    service.Send(id, e.ByteBlock);
                }
                if (tcpClientLeft.Online)
                {
                    tcpClientLeft.Send(e.ByteBlock.Buffer, 0, e.ByteBlock.Len);
                }
                return EasyTask.CompletedTask;
            };

        }

        private void dungeonToggleButton1_ToggledChanged()
        {
            try
            {
                if (dungeonToggleButton1.Toggled)
                {
                    groupBox1.Enabled = false;

                    if (dungeonComboBox1.SelectedIndex == 0)
                    {
                        service.AddListen(new TcpListenOption()
                        {
                            IpHost = $"{dungeonTextBox1.Text}:{dungeonTextBox2.Text}",
                            Name = "server1",//名称用于区分监听
                        });
                    }
                    else if (dungeonComboBox1.SelectedIndex == 1)
                    {
                        tcpClientLeft.Setup(new TouchSocketConfig().SetRemoteIPHost($"{dungeonTextBox1.Text}:{dungeonTextBox2.Text}").ConfigurePlugins(a =>
                        {
                            a.UseReconnection(-1, true, 1000);
                        }));
                        tcpClientLeft.Connect();
                    }
                }
                else
                {
                    groupBox1.Enabled = true;

                    foreach (var item in service.Monitors)
                    {
                        if (item.Option.IpHost.Port == Convert.ToInt32(dungeonTextBox2.Text))
                        {
                            service.RemoveListen(item);
                        }
                    }

                    tcpClientLeft.Close();
                }
            }
            catch (Exception)
            {

            }
        }

        private void dungeonToggleButton2_ToggledChanged()
        {
            try
            {
                if (dungeonToggleButton2.Toggled)
                {
                    groupBox2.Enabled = false;

                    if (dungeonComboBox2.SelectedIndex == 0)
                    {
                        service.AddListen(new TcpListenOption()
                        {
                            IpHost = $"{dungeonTextBox4.Text}:{dungeonTextBox3.Text}",
                            Name = "server2",//名称用于区分监听
                        });
                    }
                    else if (dungeonComboBox2.SelectedIndex == 1)
                    {
                        tcpClientRight.Setup(new TouchSocketConfig().SetRemoteIPHost($"{dungeonTextBox4.Text}:{dungeonTextBox3.Text}").ConfigurePlugins(a =>
                        {
                            a.UseReconnection(-1, true, 1000);
                        }));
                        tcpClientRight.Connect();
                    }
                }
                else
                {
                    groupBox2.Enabled = true;

                    foreach (var item in service.Monitors)
                    {
                        if (item.Option.IpHost.Port == Convert.ToInt32(dungeonTextBox3.Text))
                        {
                            service.RemoveListen(item);
                        }
                    }
                    tcpClientRight.Close();
                }
            }
            catch (Exception)
            {

            }
        }

        //变灯
        private void SentOnlineColor()
        {
            var ids = service.GetIds();

            if (dungeonComboBox1.SelectedIndex == 0)
                badge1.Value = ids.Where(it => it.Contains($"ServicePort:{dungeonTextBox2.Text}")).Count();
            else if (dungeonComboBox1.SelectedIndex == 1)
                if (tcpClientLeft.Online)
                    badge1.Value = 1;
                else
                    badge1.Value = 0;

            if (dungeonComboBox2.SelectedIndex == 0)
                badge2.Value = ids.Where(it => it.Contains($"ServicePort:{dungeonTextBox3.Text}")).Count();
            else if (dungeonComboBox2.SelectedIndex == 1)
                if (tcpClientRight.Online)
                    badge2.Value = 1;
                else
                    badge2.Value = 0;


            if (badge1.Value > 0)
                badge1.BGColorA = Color.Green;
            else
                badge1.BGColorA = Color.Red;

            if (badge2.Value > 0)
                badge2.BGColorA = Color.Green;
            else
                badge2.BGColorA = Color.Red;
        }
    }
}
